package com.zzyy.study.controller;

import com.zzyy.study.entities.User;
import com.zzyy.study.resp.ResultData;
import com.zzyy.study.service.UserLongTXService;
import com.zzyy.study.utils.PerformanceRunnerUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @auther zzyy
 * @create 2024-04-03 15:26
 */
@RestController
@Slf4j
public class UserLongTXController
{
    @Resource
    private UserLongTXService userLongTXService;

    // http://localhost:24414/user/addlongtx
    @PostMapping(value = "/user/addlongtx")
    public ResultData<Integer> addUser(@RequestBody User user)
    {
        Integer result = userLongTXService.addUser(user);
        return ResultData.success(result);
    }

    // http://localhost:24414/user/addoptimize
    @PostMapping(value = "/user/addoptimize")
    public int addUserOptimize(@RequestBody User user)
    {
        return userLongTXService.addUserOptimize(user);
    }

    @PostMapping(value = "/user/performance/test")
    public void test(@RequestBody User user) throws InterruptedException
    {
        //String url = "http://localhost:24414/user/addlongtx";
        String url = "http://localhost:24414/user/addoptimize";

        //对 url 指定的接口模拟200个并发请求，然后输出成功数量和失败的数量
        RestTemplate restTemplate = new RestTemplate();

        //调用压测工具类开始压测,模拟200个并发进行测试
        PerformanceRunnerUtil.PerformanceRunnerResult retValue = PerformanceRunnerUtil.performanceRun(
                200,
                200,
                () -> restTemplate.postForObject(url,user,Integer.class));

        System.out.println("\n压测结果如下：");
        System.out.println("==============================");
        System.out.println("请求总数 "+retValue.getRequests());
        System.out.println("并发量 "+retValue.getConcurrency());
        System.out.println("成功请求数 "+retValue.getSuccessRequests());
        System.out.println("失败请求数 "+retValue.getFailRequests());
        System.out.println("请求总耗时(ms) "+retValue.getTimeTakenForTests());
        System.out.println("每秒请求数(吞吐量) "+ retValue.getRequestsPerSecond());
        System.out.println("每个请求平均耗时(ms)"+ retValue.getTimePerRequest());
        System.out.println("最快的请求耗时(ms)"+ retValue.getFastestCostTime());
        System.out.println("最慢的请求耗时(ms)"+ retValue.getSlowestCostTime());
        System.out.println("==============================");



    }
}
